package com.remac.framework.mybatisplus.extensions.typehandler.json;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.remac.framework.mybatisplus.extensions.typehandler.IGenericTypeHandler;
import com.remac.framework.mybatisplus.extensions.typehandler.IJsonTypeHandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Ye Junhui
 * @since 2024/4/24
 */
public abstract class AbstractGenericJsonTypeHandler<T> extends BaseTypeHandler<T> implements IGenericTypeHandler, IJsonTypeHandler<T> {

    /**
     * 泛型类型
     */
    protected Type type;

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        final String json = rs.getString(columnName);
        return StringUtils.isBlank(json) ? null : parse(json);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        final String json = rs.getString(columnIndex);
        return StringUtils.isBlank(json) ? null : parse(json);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        final String json = cs.getString(columnIndex);
        return StringUtils.isBlank(json) ? null : parse(json);
    }

    @Override
    public void setType(Type type) {
        this.type = type;
    }

    /**
     * 写处理器
     * @return
     */
    public abstract AbstractJsonObjectTypeHandler getWriteHandler();
}
